package com.twan.kotlinbase.ui

import android.content.Intent
import android.view.View
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.jaeger.library.StatusBarUtil
import com.lxj.xpopup.XPopup
import com.next.easynavigation.view.EasyNavigationBar
import com.next.easynavigation.view.EasyNavigationBar.OnTabClickListener
import com.tencent.qcloud.tim.demo.conversation.ConversationFragment
import com.tencent.qcloud.tim.demo.login.UserInfo
import com.tencent.qcloud.tim.demo.signature.GenerateTestUserSig
import com.tencent.qcloud.tim.demo.utils.DemoLog
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack
import com.tencent.qcloud.tim.uikit.utils.ToastUtil
import com.twan.kotlinbase.R
import com.twan.kotlinbase.app.BaseDataBindingActivity
import com.twan.kotlinbase.app.isSimulater
import com.twan.kotlinbase.app.permissionArr
import com.twan.kotlinbase.bean.CatoeryNums
import com.twan.kotlinbase.bean.SettleStatus
import com.twan.kotlinbase.databinding.ActivityMainBinding
import com.twan.kotlinbase.fragment.*
import com.twan.kotlinbase.network.RxHttpScope
import com.twan.kotlinbase.pop.PublishPopup
import com.twan.kotlinbase.util.DictUtils
import com.twan.kotlinbase.util.MyUtils
import com.twan.kotlinbase.util.RxPermissionsUtil
import com.twan.kotlinbase.widgets.router.Router
import kotlinx.android.synthetic.main.activity_main.*
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse

class MainActivity : BaseDataBindingActivity<ActivityMainBinding>() {
    private val tabText = arrayOf("首页", "发现", "消息", "我的")
    //未选中icon
    private val normalIcon = intArrayOf(R.mipmap.home, R.mipmap.star, R.mipmap.msg, R.mipmap.me)
    //选中时icon
    private val selectIcon = intArrayOf(R.mipmap.home_pressed, R.mipmap.star_pressed, R.mipmap.msg_pressed, R.mipmap.me_pressed)

    companion object {
        lateinit var main:MainActivity
    }

    override fun getLayout(): Int {
        return R.layout.activity_main
    }

    override fun initEventAndData() {
        setSwipeBackEnable(false)
        main= this
        setContentView(R.layout.activity_main)
        initBottomBar()
        DictUtils.loadDict()

        var obser = mainRL.viewTreeObserver
        obser.addOnGlobalLayoutListener {
            StatusBarUtil.setColor(this@MainActivity, resources.getColor(R.color.head_bg), 0)
        }
        RxPermissionsUtil.requestPermission(this, *permissionArr){}

//        loginIM()
    }

    //页面获得焦点时(即页面加载完成)
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if(hasFocus){
           // StatusBarUtil.setColor(this@MainActivity, resources.getColor(R.color.head_bg), 0)
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        var tab = intent?.extras?.getInt("tab")
        if (tab == 3) {
            navigationBar.selectTab(3,true)
        } else if (tab == 2) {
            navigationBar.selectTab(2,true)
        } else if (tab ==1) {
            navigationBar.selectTab(1,true)
        } else {
            navigationBar.selectTab(0,true)
        }
    }

    private fun initBottomBar(){
        var fragments= mutableListOf<Fragment>()
        fragments.add(Tab1Fragment())
        //fragments.add(Tab2Fragment())//一期换掉
        fragments.add(ShopLiveFragment())
        //fragments.add(ConversationFragment()) //Tab3Fragment
        fragments.add(if (isSimulater) Tab3Fragment() else ConversationFragment()) //Tab3Fragment
        fragments.add(Tab4Fragment())

        navigationBar.titleItems(tabText)
            .normalIconItems(normalIcon)
            .selectIconItems(selectIcon)
            .fragmentList(fragments)
            .centerImageRes(R.mipmap.add_tab2)
            .centerTextStr(" ")
            .iconSize(25f)     //Tab图标大小
            .tabTextSize(12)   //Tab文字大小
            .tabTextTop(2)     //Tab文字距Tab图标的距离
            .normalTextColor(resources.getColor(R.color.text_88))
            .selectTextColor(resources.getColor(R.color.text_black))
            .centerLayoutRule(EasyNavigationBar.RULE_BOTTOM)
            .centerLayoutBottomMargin(0)
            .centerAlignBottom(true)
            .fragmentManager(supportFragmentManager)
            .textSizeType(EasyNavigationBar.TextSizeType.TYPE_DP)
            .centerTextTopMargin(-8)  //加号文字距离加号图片的距离
            .setOnTabClickListener(object : OnTabClickListener {
                override fun onTabSelectEvent(view: View, position: Int): Boolean {
                    StatusBarUtil.setColor(this@MainActivity, resources.getColor(R.color.head_bg), 0)
                    if(position == 2){
                        if(MyUtils.isLogin()){
                            return false
                        }else{
                            Router.newIntent(this@MainActivity).to(LoginActivity::class.java).launch()
                            return true
                        }
                    }else{
                        return false
                    }
                }

                override fun onTabReSelectEvent(view: View, position: Int): Boolean {
                    return false
                }
            })
            .setOnTabLoadListener {
                //navigationBar.setMsgPointCount(2, 109)
                //navigationBar.setHintPoint(1, true)只提示红点,不显示数量
            }
            .setOnCenterTabClickListener {
                XPopup.Builder(this@MainActivity).asCustom(PublishPopup(this@MainActivity)).show()

                false
            }
            .canScroll(true)
            .mode(EasyNavigationBar.NavigationMode.MODE_ADD)
            .build()
    }



    fun loginIM(){
        if (!isSimulater) { //im不支持模拟器,原因尚未清楚
            RxHttpScope().launch {
                val kefuid = if (MyUtils.isLogin()) MyUtils.getUserid() else "小肚驴游客"
//                val userSig = GenerateTestUserSig.genTestUserSig(kefuid)
                val userSig =  RxHttp.get("im/generateUserSig")
                    .add("userId", MyUtils.getUserid())
                    .toResponse<Any>().await()


                TUIKit.login(kefuid, userSig as String?, object : IUIKitCallBack {
                    override fun onError(module: String, code: Int, desc: String) {
                        runOnUiThread { ToastUtil.toastLongMessage(getString(R.string.failed_login_tip) + ", errCode = " + code + ", errInfo = " + desc) }
                        DemoLog.i("ssssssssss", "imLogin errorCode = $code, errorInfo = $desc")
                    }

                    override fun onSuccess(data: Any?) {
                        UserInfo.getInstance().setAutoLogin(true)
                        LogUtils.e("登录成功")
                    }
                })
            }
        }
    }
}